import csv
import requests
from typing import List, Dict

# 读取文档数据（假设文档为文本文件，内容为嵌套列表格式）
def read_document(file_path: str) -> List[List[str]]:
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read().strip()
        # 解析文本为嵌套列表（需根据实际格式调整，假设数据在 [["...", "...", ...], ...] 中）
        import ast
        return ast.literal_eval(content)

# 通过 Wikidata API 查询脑区功能（示例，实际需替换为专业数据库或知识库 API）
def fetch_brain_function(abbreviation: str) -> str:
    url = f"https://www.wikidata.org/w/api.php?action=wbsearchentities&search={abbreviation}&language=ch&format=json"
    try:
        response = requests.get(url,verify=False)
        data = response.json()
        if "search" in data and len(data["search"]) > 0:
            item_id = data["search"][0]["id"]
            # 获取实体描述
            desc_url = f"https://www.wikidata.org/wiki/Special:EntityData/{item_id}.json"
            desc_response = requests.get(desc_url,verify=False)
            desc_data = desc_response.json()
            description = desc_data["entities"][item_id].get("descriptions", {}).get("en", {}).get("value", "")
            return description if description else "功能待补充"
        return "功能待补充"
    except Exception as e:
        print(f"查询功能失败: {e}")
        return "功能待补充"

def process_brain_regions(file_path: str) -> List[Dict[str, str]]:
    # 读取文档数据
    raw_data = read_document(file_path)
    brain_regions = []
    # 过滤无效行（仅处理缩写和名称非空的条目）
    valid_entries = [item for item in raw_data if len(item) >= 2 and item[0] != "root" and item[0] != "unknow"]
    
    for item in valid_entries:
        abbreviation, name = item[0], item[1]
        # 调用API获取功能（实际需处理速率限制和错误）
        function = fetch_brain_function(abbreviation)
        brain_regions.append({
            "缩写": abbreviation,
            "脑区名称": name,
            "功能": function
        })
    return brain_regions

def save_to_csv(regions: List[Dict[str, str]], filename: str = "brain_regions_with_functions.csv"):
    fieldnames = ["缩写", "脑区名称", "功能"]
    with open(filename, "w", newline="utf-8", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(regions)

if __name__ == "__main__":
    # 替换为实际文件路径
    document_path = "../resource/region2.txt"
    try:
        processed_data = process_brain_regions(document_path)
        save_to_csv(processed_data)
        print(f"成功生成CSV文件，包含 {len(processed_data)} 个脑区")
    except Exception as e:
        print(f"处理失败: {e}")